package com.google.memoryofaplace;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.memoryofaplace.model.TBPlaceComments;
import com.google.memoryofaplace.model.TBPlaces;

public class BLPlaceComments {

	public static JSONObject addPlaceComment(long codPlace, String user,
			String comment, int commentType) throws JSONException {
		JSONObject jResult = new JSONObject();

		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			TBPlaces place = pm.getObjectById(TBPlaces.class,
					KeyFactory.createKey("TBPlaces", codPlace));
			if (place == null) {
				jResult = General.returnError("event " + codPlace + " not found");
			} else {

				List<TBPlaceComments> comments = place.getComments();
				if (comments == null) {
					comments = new ArrayList<TBPlaceComments>();
				}
				TBPlaceComments placeComment = new TBPlaceComments(user,
						comment, commentType);
				comments.add(placeComment);
				pm.makePersistent(place);
				pm.close();
				jResult.put("status", General.OK);
				jResult.put("date", General.formatDate(new Date()));
				jResult.put("codplacecomment",
						placeComment.getCodPlaceComment());
			}
		} catch (Exception e) {
			jResult = new JSONObject();
			jResult = General.returnError(e.getMessage());
		}
		return jResult;
	}

}
